#include "stdafx.h"
#include "Save.h"
#include<sstream>

void SaveHelper::Write(std::ostream & out, ISave & isave)
{
	std::stringbuf tmp;
	std::ostream out_tmp(&tmp);
	isave.Write(out_tmp);
	size_t size = tmp.str().size();
	out.write((char*)&size, sizeof(size_t));
	out.write(tmp.str().c_str(), size);
}
void SaveHelper::Read(std::istream & in, ISave & isave)
{
	size_t size;
	in.read((char*)&size, sizeof(size_t));
	char * tmp_buf = new char[size];
	in.read(tmp_buf, size);
	std::stringbuf tmp;
	std::iostream in_tmp(&tmp);
	in_tmp.write(tmp_buf, size);
	delete tmp_buf;
	isave.Read(in_tmp);
}

void SaveHelper::Write(std::ostream & out, std::wstring str)
{
	size_t size = str.size() * sizeof(wchar_t);
	out.write((char*)&size, sizeof(size_t));
	if (size == 0)return;
	out.write((char*)str.c_str(), size);
}

void SaveHelper::Read(std::istream & in, std::wstring & str)
{
	size_t size = 0;
	in.read((char*)&size, sizeof(size_t));
	if (size == 0)return;
	char*buf = new char[size];
	in.read(buf, size);
	for (size_t i = 0; i < size; i += 2)
	{
		wchar_t ch = (buf[i] & 0x00ff) | ((buf[i + 1] << 8) & 0xff00);
		str += ch;
	}
	delete[]buf;
}

void SaveHelper::Write(std::ostream & out, std::string str)
{
	size_t size = str.size() * sizeof(char);
	out.write((char*)&size, sizeof(size_t));
	if (size == 0)return;
	out.write((char*)str.c_str(), size);
}

void SaveHelper::Read(std::istream & in, std::string & str)
{
	size_t size = 0;
	in.read((char*)&size, sizeof(size_t));
	if (size == 0)return;
	char*buf = new char[size];
	in.read(buf, size);
	std::stringstream ss;
	ss.write(buf, size);
	str = ss.str();
	delete[]buf;
}


void SaveHelper::Write(std::ostream & out, bool n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, bool & n)
{
	in.read((char*)&n, sizeof(n));
}

void SaveHelper::Write(std::ostream & out, unsigned int n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, unsigned int & n)
{
	in.read((char*)&n, sizeof(n));
}

void SaveHelper::Write(std::ostream & out, int n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, int & n)
{
	in.read((char*)&n, sizeof(n));
}

void SaveHelper::Write(std::ostream & out, long n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, long & n)
{
	in.read((char*)&n, sizeof(n));
}

void SaveHelper::Write(std::ostream & out, unsigned long n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, unsigned long & n)
{
	in.read((char*)&n, sizeof(n));
}


void SaveHelper::Write(std::ostream & out, float n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, float & n)
{
	in.read((char*)&n, sizeof(n));
}

void SaveHelper::Write(std::ostream & out, double n)
{
	out.write((char*)&n, sizeof(n));
}

void SaveHelper::Read(std::istream & in, double & n)
{
	in.read((char*)&n, sizeof(n));
}
